package com.itheima.service.impl;

import com.aliyuncs.utils.StringUtils;
import com.fasterxml.jackson.databind.annotation.JsonAppend;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.common.entity.PageResult;
import com.itheima.common.entity.QueryPageBean;
import com.itheima.mapper.CheckGroupMapper;
import com.itheima.mapper.SetmealMapper;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.CheckItem;
import com.itheima.pojo.Setmeal;
import com.itheima.service.CheckItemService;
import com.itheima.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.io.FileWriter;
import java.io.IOException;
import java.util.*;

@Service
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private CheckGroupMapper checkGroupMapper;
    /**
     * 获取所有套餐信息
     * @return
     */
    @Override
    public List<Setmeal> getSetmeal() {
        //拿到所有套餐
        List<Setmeal> setmeals = setmealMapper.getSetmeal();
        setmeals = setCheckGroups(setmeals);
        return setmeals;
    }

    /**
     * 分页查询检查项
     * @param pageBean
     * @return
     */
    @Override
    public PageResult findPage(QueryPageBean pageBean) {
        PageHelper.startPage(pageBean.getCurrentPage(), pageBean.getPageSize());
        Page<CheckItem> list = setmealMapper.findPage(pageBean.getQueryString());

        PageResult result = new PageResult(list.getTotal(),list.getResult());
        return result;
    }


    @Override
    public Setmeal findById(Integer id) {
        Setmeal setmeal = setmealMapper.findById(id);
        List<Setmeal> list = new ArrayList<>();
        list.add(setmeal);
        list = setCheckGroups(list);
        return list.get(0);
    }

    @Override
    public void edit(Setmeal setmeal, String checkgroupIds) {
        //修改套餐
        setmealMapper.edit(setmeal);
        //删除套餐与检查组的关系
        setmealMapper.deleteCheckgroupBySetmealId(setmeal.getId());
        //新增套餐与检查组的关系
        setmealMapper.addSetmealCheckgroup(setmeal.getId(),ids(checkgroupIds));
    }

    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private Configuration configuration;
    @Autowired
    private CheckItemService checkItemService;

    @Override
    public void add(Setmeal setmeal, String checkgroupIds) throws Exception{
        //修改图片名字格式
        String[] split = setmeal.getImg().split("/");
        setmeal.setImg(split[3]);
        //新增套餐且获得id
        setmealMapper.add(setmeal);
        //新增套餐与检查组的关系
        setmealMapper.addSetmealCheckgroup(setmeal.getId(),ids(checkgroupIds));
        //将图片名称保存到redis
        ValueOperations valueOperations = redisTemplate.opsForValue();
        //格式为名称:路径
        valueOperations.set(split[3],setmeal.getImg());

        build();

    }

    public void build() throws Exception {
        //获取所有的套餐数据
        List<Setmeal> list = getSetmeal();
        for (Setmeal sm : list) {
            if (sm.getRemark() == null) sm.setRemark("");
            if (sm.getAttention() == null) sm.setAttention("");
            if (sm.getImg() == null) sm.setImg("");
            if (sm.getCheckGroups() == null) sm.setCheckGroups(new ArrayList<>());
            else {
                ArrayList<CheckItem> checkItems;
                for (CheckGroup checkGroup : sm.getCheckGroups()) {
                    if(checkGroup == null){
                        sm.setCheckGroups(new ArrayList<>());
                        break;
                    }
                    checkItems = new ArrayList<>();
                    List<Integer> checkItemIdsByCheckGroupId = checkItemService.findCheckItemIdsByCheckGroupId(checkGroup.getId());
                    if(checkItemIdsByCheckGroupId == null) {
                        checkGroup.setCheckItems(new ArrayList<>());
                        break;
                    }
                    for (Integer i : checkItemIdsByCheckGroupId) {
                        CheckItem checkItem = checkItemService.findById(i);
                        checkItems.add(checkItem);
                    }
                    checkGroup.setCheckItems(checkItems);
                }
            }
        }
        createListHtml(list);
        createDetailHtml(list);
    }

    /**
     * 生成列表页
     * @param list
     * @throws Exception
     */
    public void createListHtml(List<Setmeal> list) throws Exception{
        //freemarket的模板对象 获取模板
        Template template = configuration.getTemplate("mobile_setmeal.ftl");
        Map<String,Object> map = new HashMap<>();
        map.put("setmealList",list);
        //生成到客户端
        template.process(map,
                new FileWriter("D:\\bxg_health\\bxg-health-parent\\bxg-health-mobile\\src\\main\\resources\\mobile\\pages\\setmeal.html"));
    }

    /**
     * 生成列表页
     * @param list
     * @throws Exception
     */
    public void createDetailHtml(List<Setmeal> list) throws Exception{
        Template template = configuration.getTemplate("mobile_setmeal_detail.ftl");
        for (Setmeal sm : list) {
            Map<String, Object> map = new HashMap<>();
            map.put("setmeal", sm);
            //生成到客户端
            template.process(map,
                    new FileWriter("D:\\bxg_health\\bxg-health-parent\\bxg-health-mobile\\src\\main\\resources\\mobile\\pages\\setmeal_detail_"
                            + sm.getId() + ".html"));
        }
    }

    /**
     * 获取检查组id列表
     * @param checkgroupIds
     * @return
     */
    private List<Integer> ids(String checkgroupIds){
        List<Integer> list = new ArrayList<>();
        String[] split = checkgroupIds.split(",");
        for (String s : split) {
            list.add(Integer.valueOf(s));
        }
        return list;
    }

    /**
     * 封装套餐对应的检查组信息
     * @param setmeals
     * @return
     */
    private List<Setmeal> setCheckGroups(List<Setmeal> setmeals){
        for (Setmeal setmeal : setmeals) {
            Integer id = setmeal.getId();
            //拿到套餐关联检查项的id
            List<Integer> list = checkGroupMapper.getCheckGroupsBySetmealId(id);

            //拿到所有相关检查项
            List<CheckGroup> checkGroups = new ArrayList<>();
            for (Integer i : list) {
                checkGroups.add(checkGroupMapper.getById(i));
            }

            //封装
            setmeal.setCheckGroups(checkGroups);
        }
        return setmeals;
    }
}
